import SparkMD5 from 'spark-md5';
export function getFileMd5(file: File): Promise<[null|string, string]> {
    // @ts-ignore
    const blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice,
        chunkSize = 2097152, // Read in chunks of 2MB
        chunks = Math.ceil(file.size / chunkSize),
        spark = new SparkMD5.ArrayBuffer(),
        fileReader = new FileReader();
    let currentChunk = 0;
    return new Promise(resolve => {
        function loadNext() {
            var start = currentChunk * chunkSize,
                end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
    
            fileReader.readAsArrayBuffer(blobSlice.call(file, start, end));
        }
        fileReader.onerror = function () {
            resolve(['error!', ''])
        };
        fileReader.onload = function (e: any) {
            spark.append(e.target.result);
            currentChunk++;
            if (currentChunk < chunks) {
                loadNext();
            } else {
                // console.log('finished loading');
                // console.info('computed hash', spark.end());
                resolve([null, spark.end()]);
            }
        };
        loadNext();
    });
}